package gr.teiath.newsfeed;

import java.sql.Date;
import java.util.Locale;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

public class NewsView extends Activity{
		
	private static final String tag = "NewsView";
	private static NewsfeedApplication newsfeed;	
	private static String NEWS_ID;
    private static String PARSE_URL;
    private static int PARSE_TYPE;
    private static Cursor CURSOR;
    private static TextView TITLE;
    private static TextView DEPARTMENT_NAME;
    private static TextView DATE;
    private static TextView LAST_UPDATE;
    private static WebView WEBVIEW;
    private static ProgressDialog PROGRESS_DIALOG;
    private static boolean REFRESH = false;
    private static String WEB_LAYOUT = "" +
    		"<?xml version='1.0' encoding='utf-8'?>" +
    		"<style type=\"text/css\">" +
    		"	body { color:#003F75; }" + //darkBlue color
    		"	a:link { color:#7F3B00; }" + //brown color
    		"</style>" +
    		"<html>" +
    		"	<body>" +
    		"	%s" +
    		"	</body>" +
    		"</html>";
	
    @Override
	public boolean onCreateOptionsMenu(Menu newsviewmenu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.newsviewmenu, newsviewmenu);
		return true;
	}
    
    public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuViewInBrowser:
			newsfeed.externalLink(PARSE_URL);		
			break;
			
		case R.id.menuRefreshNewsView:
			if(NewsfeedApplication.getNetworkConnectivity()){
				PROGRESS_DIALOG = ProgressDialog.show(this, this.getString(R.string.refreshingContentTitle), this.getString(R.string.refreshingContentMsg), true);
				RefreshContentTask refreshTask = new RefreshContentTask();
				refreshTask.execute();
			} else {
				Toast.makeText(this, this.getText(R.string.noConnection), Toast.LENGTH_SHORT).show();
			}
			break;
		}
		return true;
	}
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        newsfeed = (NewsfeedApplication) getApplication();
        setContentView(R.layout.newsview);
	}
	
	public void onResume() {
		super.onResume();
		
		if(!REFRESH) {
			Intent newsView = getIntent();
			
			NEWS_ID = newsView.getStringExtra("_id");
			PARSE_URL = newsView.getStringExtra("link");
			PARSE_TYPE = newsView.getIntExtra("p_type", 2);
			//FACULTY_NAME = newsView.getStringExtra("faculty_name");
			//hasContent = newsView.getBooleanExtra("content", false);
			//isExternal = newsView.getBooleanExtra("external", false);
		}
		
		// TODO ?? Make an AsyncTask
		CURSOR = newsfeed.readContent(NEWS_ID);
		
		//Print results to screen
		Log.i(tag, "****** NewsView // Printing Results");
    	TITLE = (TextView) findViewById(R.id.titleView);
    	TITLE.setText(CURSOR.getString(CURSOR.getColumnIndex("name")));
    	
    	DEPARTMENT_NAME = (TextView) findViewById(R.id.departmentView);
    	DEPARTMENT_NAME.setText(CURSOR.getString(CURSOR.getColumnIndex("faculty_name")));
    	
    	WEBVIEW = (WebView) findViewById(R.id.webView); 
    	WEBVIEW.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    	WEBVIEW.setBackgroundColor(0);
    	
        String uri = Uri.encode(String.format(Locale.US, WEB_LAYOUT, CURSOR.getString(CURSOR.getColumnIndex("content"))));
        WEBVIEW.loadData(uri, "text/html", "UTF-8");
    	
    	DATE = (TextView) findViewById(R.id.dateView);
    	DATE.setText(DateFormat.format("dd/MM/yy", Date.valueOf(CURSOR.getString(CURSOR.getColumnIndex("date")))));
    	
    	LAST_UPDATE = (TextView) findViewById(R.id.lastUpdate);
    	LAST_UPDATE.setText(this.getString(R.string.LastUpdate) + " " + DateFormat.format("dd/MM/yy", Date.valueOf(CURSOR.getString(CURSOR.getColumnIndex("date")))));
    	
    	REFRESH = false;
    }
	
	public void onPause() {
		super.onPause();
		CURSOR.close(); // startManagingCursor is being deprecated
	}
	
	private static class RefreshContentTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			return newsfeed.refreshContent(NEWS_ID, PARSE_URL, PARSE_TYPE);
			
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			
			//TODO Remove debug String and update Last Update date
			String uri = Uri.encode(String.format(Locale.US, WEB_LAYOUT, "<p>:: REFRESHED VIEW ::</p>" + CURSOR.getString(CURSOR.getColumnIndex("content")).trim()));
	        WEBVIEW.loadData(uri, "text/html", "UTF-8");
			if(PROGRESS_DIALOG != null && PROGRESS_DIALOG.isShowing()) PROGRESS_DIALOG.dismiss();
		}
	}
}
